package files.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import files.service.IFilesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.UUID;


@Service
public class FilesServiceImpl implements IFilesService {
    
    private static final Logger logger = LoggerFactory.getLogger(FilesServiceImpl.class);
    
    @Autowired
    private OSS ossClient;
    
    @Autowired
    private String bucketName;
    
    @Autowired
    private String baseUrl;
    
    @Autowired
    private String baseDir;
    
    @Override
    public Result uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            logger.error("上传文件为空");
            return Result.failure(ResultCodeEnum.FAIL, "上传文件不能为空");
        }
        
        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 使用UUID生成唯一文件名
            String fileName = UUID.randomUUID().toString() + suffix;
            
            // 按年月日生成目录
            LocalDate now = LocalDate.now();
            String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            
            // 文件存储路径
            String filePath = baseDir + datePath + "/" + fileName;
            
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream);
            
            // 上传文件到OSS
            ossClient.putObject(putObjectRequest);
            
            // 获取文件访问路径
            String url = baseUrl + "/" + filePath;
            
            logger.info("文件上传成功，访问地址: {}", url);
            
            // 返回成功结果和文件访问路径
            return Result.success(url);
            
        } catch (IOException e) {
            logger.error("文件上传失败: {}", e.getMessage());
            return Result.failure(ResultCodeEnum.FAIL, "文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("OSS上传异常: {}", e.getMessage());
            return Result.failure(ResultCodeEnum.FAIL, "文件上传异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result saveBase64Image(String base64Image) {
        if (base64Image == null || base64Image.isEmpty()) {
            logger.error("Base64图片数据为空");
            return Result.failure(ResultCodeEnum.FAIL, "Base64图片数据不能为空");
        }
        
        try {
            // 去除base64前缀，如"data:image/jpeg;base64,"
            String base64Data = base64Image;
            if (base64Image.contains(",")) {
                base64Data = base64Image.substring(base64Image.indexOf(",") + 1);
            }
            
            // 解码Base64数据
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            
            // 确定图片类型
            String suffix = ".jpg"; // 默认为jpg
            if (base64Image.contains("data:image/")) {
                String mimeType = base64Image.substring(base64Image.indexOf("data:image/") + 11, base64Image.indexOf(";base64"));
                suffix = "." + mimeType;
            }
            
            // 使用UUID生成唯一文件名
            String fileName = UUID.randomUUID().toString() + suffix;
            
            // 按年月日生成目录
            LocalDate now = LocalDate.now();
            String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            
            // 文件存储路径
            String filePath = baseDir + datePath + "/" + fileName;
            
            // 创建输入流
            InputStream inputStream = new ByteArrayInputStream(imageBytes);
            
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream);
            
            // 上传文件到OSS
            ossClient.putObject(putObjectRequest);
            
            // 获取文件访问路径
            String url = baseUrl + "/" + filePath;
            
            logger.info("Base64图片上传成功，访问地址: {}", url);
            
            // 返回成功结果和文件访问路径
            return Result.success(url);
            
        } catch (IllegalArgumentException e) {
            logger.error("Base64解码失败: {}", e.getMessage());
            return Result.failure(ResultCodeEnum.FAIL, "Base64图片格式不正确: " + e.getMessage());
        } catch (Exception e) {
            logger.error("Base64图片上传异常: {}", e.getMessage());
            return Result.failure(ResultCodeEnum.FAIL, "Base64图片上传异常: " + e.getMessage());
        }
    }
}
